package com.source.module_kotlin_library.fragment

import android.os.Bundle
import android.os.Handler
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewStub
import com.source.module_kotlin_library.R
import com.source.module_kotlin_library.adapter.WorldAdapter
import com.source.module_kotlin_library.utils.KTToastUtils
import kotlinx.android.synthetic.main.fragment_world.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.random.Random

/**
 * 世界
 */
class WorldFragment : Fragment() {
    private var tipList = ArrayList<String>()
    lateinit var recycler: RecyclerView
    lateinit var emptyView: ViewStub
    private var dataList = ArrayList<String>()
    lateinit var worldAdapter: WorldAdapter
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        var view = inflater.inflate(R.layout.fragment_world, null)
        recycler = view.findViewById(R.id.recycler)
        emptyView = view.findViewById(R.id.emptyView)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        var coroutineScope = CoroutineScope(EmptyCoroutineContext)
        coroutineScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.Default) {
                initData()
            }
            initListener()
        }
//        initData()
//        initListener()
    }

    /**
     * 初始化数据
     */
    fun initData() {
        tipList.add("初始化数据")
        tipList.add("初始化数据初始化数据初始化数据初始化数据初始化数据初始化数据初始化数据初始化数据初始化数据")
        repeat(100) {
            dataList.add("${tipList[Random.nextInt(2)]}${it + 1}")
        }
    }

    /**
     * 注册监听
     */
    fun initListener() {
        worldAdapter = WorldAdapter(context!!, dataList)
        recycler?.let {
            it.layoutManager = LinearLayoutManager(context)
//            it.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
            it.adapter = worldAdapter
            worldAdapter.setOnItemClickListener(object : WorldAdapter.MyItemClickListener {
                override fun onItemClick(str: String) {
                    KTToastUtils.showToast(context!!, str)
                }

            })
        }
        recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            //用来标记是否正在向最后一个滑动
            var isSlidingToLast = false
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                val manager = recyclerView.layoutManager as LinearLayoutManager
                // 当不滚动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //获取最后一个完全显示的ItemPosition
                    val firstVisibleItem = manager.findFirstCompletelyVisibleItemPosition()
                    val lastVisibleItem = manager.findLastCompletelyVisibleItemPosition()
                    val totalItemCount = manager.itemCount
                    // 判断是否滚动到顶部
                    if (firstVisibleItem == 0) {
                        tvTopLoading.visibility = View.VISIBLE
                        Handler().postDelayed({
                            tvTopLoading.visibility = View.GONE
                        }, 1500)
                    }

                    // 判断是否滚动到底部，并且是向右滚动
//                    if (lastVisibleItem == totalItemCount - 1 && isSlidingToLast) {
                    //加载更多功能的代码
//                    }
                    // 判断是否滚动到底部
                    if (lastVisibleItem == totalItemCount - 1) {
                        //加载更多功能的代码
//                        KTToastUtils.showToast(context!!, "已经到底了")
                        tvBottomLoading.visibility = View.VISIBLE
                        Handler().postDelayed({
                            tvBottomLoading.visibility = View.GONE
                        }, 1500)
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
                isSlidingToLast = if (dx > 0) {
                    //大于0表示正在向右滚动
                    true
                } else {
                    //小于等于0表示停止或向左滚动
                    false
                }
            }
        })
    }
}